package com.heima.search.service.impl;

import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.model.search.dtos.SearchHistoryDelDto;
import com.heima.model.search.dtos.SearchHistoryQueryDTO;
import com.heima.search.service.SearchHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class SearchHistoryServiceImpl implements SearchHistoryService {

    private static final String KEY_PREFIX = "leadnews:search:";

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public void del(SearchHistoryDelDto dto) {
        String key = buildKey(dto.getId(), dto.getEquipmentId());
        redisTemplate.opsForZSet().remove(key,"");
    }

    @Override
    public List<String> load(SearchHistoryQueryDTO dto) {

        String key = buildKey(UserThreadLocalUtils.getUserId(), dto.getEquipmentId());
        Set<String> set = redisTemplate.boundZSetOps(key).reverseRangeByScore(0, Double.MAX_VALUE);
        return new ArrayList<String>(set);

    }

    @Override
    @Async("taskExecutor")
    public void asyncSaveSearchHistory(Integer userId, String equimentId, String searchWords) {
       String key = buildKey(userId,equimentId);
       redisTemplate.boundZSetOps(key).incrementScore(searchWords,1);

    }

    private String buildKey(Integer userId, String equimentId) {
        if (userId == null || userId <= 0){
            return KEY_PREFIX + equimentId;
        }else {
            return KEY_PREFIX + userId;
        }

    }
}
